import 'dart:convert';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';

class IdentityPage extends StatefulWidget {
  IdentityPage({Key key}) : super(key: key);

  @override
  _IdentityPage createState() => _IdentityPage();
}

class _IdentityPage extends State<IdentityPage> {
  Asset phont1, photo2;
  String token = "", name = "", number = "";
  @override
  void initState() {
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text(
          "实名认证",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.2,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
      ),
      body: Container(
        width: double.infinity,
        child: new Column(
          children: <Widget>[
            Padding(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              child: Text(
                '请填写您的真实信息，通过后不可更改',
                style: TextStyle(
                    color: black,
                    fontSize: ScreenUtil.getInstance().setSp(MINI_FONT_SIZE)),
              ),
            ),
            Container(
              color: Colors.white,
              padding: EdgeInsets.only(left: 10),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    width: ScreenUtil.getInstance().setWidth(DP_150),
                    child: Text(
                      '真实姓名',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: black_99),
                    ),
                  ),
                  Expanded(
                    child: TextField(
                      keyboardAppearance: Brightness.light,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                          color: black_99),
                      onChanged: (value) {
                        name = value;
                      },
                      minLines: 1,
                      cursorColor: mainColor,
                      decoration: new InputDecoration(
                          contentPadding: EdgeInsets.all(5),
                          hintText: "请填写身份证上对应的姓名",
                          border: InputBorder.none),
                    ),
                    flex: 3,
                  ),
                ],
              ),
            ),
            Container(
              height: 1,
            ),
            Container(
              color: Colors.white,
              padding: EdgeInsets.only(left: 10),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    width: ScreenUtil.getInstance().setWidth(DP_150),
                    child: Text(
                      '身份证号',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: black_99),
                    ),
                  ),
                  Expanded(
                    child: TextField(
                      keyboardAppearance: Brightness.light,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                          color: black_99),
                      onChanged: (value) {
                        number = value;
                      },
                      minLines: 1,
                      cursorColor: mainColor,
                      decoration: new InputDecoration(
                          contentPadding: EdgeInsets.all(5),
                          hintText: "请填写身份证号",
                          border: InputBorder.none),
                    ),
                    flex: 3,
                  ),
                ],
              ),
            ),
            Padding(
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              child: Text(
                '请上传真实身份证照片',
                style: TextStyle(
                    color: black,
                    fontSize: ScreenUtil.getInstance().setSp(MINI_FONT_SIZE)),
              ),
            ),
            Container(
              color: white,
              width: double.infinity,
              padding: EdgeInsets.all(10),
              child: Text(
                '请保证身份证清洗可见，否则无法通过审核，我们不会泄漏个人信息',
                style: TextStyle(
                    color: black,
                    fontSize:
                        ScreenUtil.getInstance().setSp(NINIEST_FONT_SIZE)),
              ),
            ),
            Container(
              width: double.infinity,
              color: white,
              padding: EdgeInsets.all(10),
              child: Row(
                children: <Widget>[
                  Expanded(
                      child: GestureDetector(
                    child: phont1 == null
                        ? Image.asset(
                            "images/icd_l.png",
                            width: (MediaQuery.of(context).size.width - 30) / 2,
                            height: (MediaQuery.of(context).size.width - 30) /
                                2 /
                                1.585,
                            fit: BoxFit.fill,
                          )
                        : AssetThumb(
                            asset: phont1,
                            width:
                                ((MediaQuery.of(context).size.width - 30) / 2)
                                    .floor(),
                            height: ((MediaQuery.of(context).size.width - 30) /
                                    2 /
                                    1.585)
                                .floor(),
                          ),
                    onTap: () {
                      selPhoto1();
                    },
                  )),
                  Container(width: 10),
                  Expanded(
                      child: GestureDetector(
                    onTap: () {
                      selPhoto2();
                    },
                    child: photo2 == null
                        ? Image.asset(
                            "images/icd_r.png",
                            width: (MediaQuery.of(context).size.width - 30) / 2,
                            height: (MediaQuery.of(context).size.width - 30) /
                                2 /
                                1.585,
                            fit: BoxFit.fill,
                          )
                        : AssetThumb(
                            asset: photo2,
                            width:
                                ((MediaQuery.of(context).size.width - 30) / 2)
                                    .floor(),
                            height: ((MediaQuery.of(context).size.width - 30) /
                                    2 /
                                    1.585)
                                .floor(),
                          ),
                  ))
                ],
              ),
            ),
            new Container(
              width: double.infinity,
              margin: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_60)),
              height: ScreenUtil.getInstance().setHeight(DP_60),
              decoration: new BoxDecoration(
                  color: mainColor,
                  borderRadius: BorderRadius.circular(
                      ScreenUtil.getInstance().setHeight(DP_60))),
              child: new FlatButton(
                child: new Padding(
                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: new Text(
                    "提交认证",
                    style: new TextStyle(
                        color: Colors.white,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                  ),
                ),
                onPressed: () {
                  if (name == "" ||
                      number == "" ||
                      phont1 == null ||
                      photo2 == null) {
                    Fluttertoast.showToast(msg: "请填写完整信息后提交");
                    return;
                  }
                  showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (_) {
                        return new NetLoadingDialog(
                          loadingText: "提交认证中...",
                          bgColor: Color.fromARGB(255, 0, 0, 0),
                          requestCallBack: null,
                          outsideDismiss: false,
                        );
                      });
                  up();
                },
              ),
            )
          ],
        ),
      ),
    );
  }

  up() async {
    ByteData byteData = await phont1.getByteData();
    List<int> imageData = byteData.buffer.asUint8List();
    MultipartFile file =
        MultipartFile.fromBytes(imageData, filename: phont1.name);
    ByteData byteData2 = await photo2.getByteData();
    List<int> imageData2 = byteData2.buffer.asUint8List();
    MultipartFile file2 =
        MultipartFile.fromBytes(imageData2, filename: photo2.name);
                print(file2.filename);

    Map map = new Map();
    map['token'] = token;
    map['sign_type'] = SignType.USER_AUTH;
    map['img_positive'] = file;
    map['img_opposite'] = file2;
    map['truename'] = name;
    map['id_num'] = number;
    Response<String> response =
        await HttpUtil().post(Api.IDENTITY, data: getSign(map));
    Map userMap = json.decode(response.data);
    Navigator.of(context).pop(1);
    if (userMap['code'] == 1 && mounted) {
      Fluttertoast.showToast(msg: "提交成功,请等待审核");
      Navigator.of(context).pop();
    } else {
      Fluttertoast.showToast(msg: userMap['msg']);
    }
  }

  Future<void> selPhoto1() async {
    List<Asset> resultList;
    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 1,
        enableCamera: true,
        materialOptions: MaterialOptions(
          actionBarTitle: "选择图片",
          allViewTitle: "已选择",
          actionBarColor: "#F1120D",
          actionBarTitleColor: "#ffffff",
          lightStatusBar: false,
          statusBarColor: "#F1120D",
          startInAllView: true,
          selectCircleStrokeColor: "#F1120D",
          selectionLimitReachedText: "已超出",
        ),
      );
    } on Exception catch (e) {
//      error = e.message;
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    if (resultList == null&&resultList.length<=0) {
      return;
    }
    phont1 = resultList[0];
    setState(() {});
  }

  Future<void> selPhoto2() async {
    List<Asset> resultList;
    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 1,
        enableCamera: true,
        materialOptions: MaterialOptions(
          actionBarTitle: "选择图片",
          allViewTitle: "已选择",
          actionBarColor: "#F1120D",
          actionBarTitleColor: "#ffffff",
          lightStatusBar: false,
          statusBarColor: "#F1120D",
          startInAllView: true,
          selectCircleStrokeColor: "#F1120D",
          selectionLimitReachedText: "已超出",
        ),
      );
    } on Exception catch (e) {
//      error = e.message;
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    if (resultList == null&&resultList.length<=0) {
      return;
    }
    photo2 = resultList[0];
    setState(() {});
  }
}
